package com.srwl.mytx.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.LoginActivity;
import com.srwl.mytx.activity.UserProfileActivity;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.MoonUtils;
import com.srwl.mytx.utils.Utils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by wei on 2016/7/25.
 */
public class UserDetailsDialog extends BottomSheetDialog {

    Unbinder unbinder;
    @BindView(R.id.tv_anchor_nick)
    TextView usernameView;
    //    @BindView(R.id.btn_mentions)
//    Button mentionBtn;
    @BindView(R.id.iv_avatar)
    ImageView iv_avatar;
    @BindView(R.id.tx_follow)
    TextView tv_follow;
    @BindView(R.id.tv_fans_num)
    TextView tv_fans_num;
    @BindView(R.id.tv_follow_num)
    TextView tv_follow_num;
    @BindView(R.id.tv_donation_amount)
    TextView tv_donationAmount;
    @BindView(R.id.tv_gender)
    TextView tv_gender;
    @BindView(R.id.tv_area)
    TextView tv_area;

    private User user;
    private String TAG = "UserDetailsDialog";
    private boolean isAttention;
    private String loginUserId;
    private Long fansNum;
    private Long attentionSize;
    private Context context;

    public UserDetailsDialog(@NonNull Context context, User user) {
        super(context, R.style.BottomDialog);
        this.context = context;
        this.user = user;
        init();
    }

    private void init() {
        setContentView(R.layout.fragment_room_user_details);
        ButterKnife.bind(this);
        loginUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();

        if (user != null) {
            if (user.getUsername() != null) {
                usernameView.setText(user.getUsername());
            } else {
                usernameView.setText(user.getNick());
            }

            GlideLoadUtils.glideLoad(context, user.getAvatar(), iv_avatar, R.drawable.tx_default_avatar_1);
            String donationString = Utils.moneyFormat(user.getDonationAmount());
            tv_donationAmount.setText(MoonUtils.getSpannableString_red(context, donationString));
            if (user.getGender() != null) {
                if (user.getGender().equals(1)) {
                    tv_gender.setText("女");
                } else if (user.getGender().equals(0)) {
                    tv_gender.setText("男");
                }
            } else {
                tv_gender.setVisibility(View.GONE);
            }
            tv_area.setText(user.getArea());

            if ((user.getFans() == null || user.getAttentionSize() == null) && !Utils.isTempUser(user)) { //当不是临时用户的时候，才需要去后端加载数据，临时用户是没有粉丝的
                checkFollow(user.getuId());
            } else {
                fansNum = user.getFans();
                attentionSize = user.getAttentionSize();
                String fansString = Utils.numberFormat(fansNum);
                tv_fans_num.setText(MoonUtils.getSpannableString(context, fansString));//显示图片数字，数字替换成对应的图片
                String attentionString = Utils.numberFormat(attentionSize);
                tv_follow_num.setText(MoonUtils.getSpannableString(context, attentionString));
                isAttention = user.isAttention();
                if (isAttention) {
                    tv_follow.setText("已关注");
                }

            }

        }
    }


//    public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                             Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.fragment_room_user_details, container, false);
//        unbinder = ButterKnife.bind(this, view);
//        return view;
//    }

//    @Override
//    public void onActivityCreated(Bundle savedInstanceState) {
//        super.onActivityCreated(savedInstanceState);
//        loginUserId = UserProfileManager.getInstance().getLoginUserInfo().getuId();
//        if (getArguments() != null) {
//            user = getArguments().getParcelable("USER");
//        }
//        if (user != null) {
//            usernameView.setText(user.getUsername());
//            Glide.with(UserDetailsDialog.this).load(user.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.tx_default_avatar).into(iv_avator);
//            checkFollow(user.getuId());
//            if (user.getUId().equals(loginUserId)) {
//                btn_follow.setVisibility(View.INVISIBLE);
//                btn_message.setVisibility(View.INVISIBLE);
//            }
//        }
//        // mentionBtn.setText("@TA");
//    }

    @OnClick(R.id.iv_avatar)
    void onAvatarBtnClick() {
        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, user).putExtra(Constant.SYNC_USER_INFO, false));

    }

    @OnClick(R.id.rl_message)
    void onMessageBtnClick() {
        if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
            getContext().startActivity(new Intent(getContext(), LoginActivity.class).putExtra("EXTRA_CONTENT", "发消息需要先登录"));
            return;
        }

        if (user.getUId().equals(loginUserId)) {
            ConfirmDialog dialog = new ConfirmDialog(context, "提示", "不能向自己发消息");
            dialog.show();
            return;
        }
        if (dialogListener != null) {
            user.setType(Constant.USER_TYPE_TEMP );//把目标联系人的类型设置为临时状态
            dialogListener.onMessageClick(user);
        }

        // getActivity().getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.message_container, fragment).commit();
    }

  /*  @OnClick(R.id.btn_mentions)
    void onMentionBtnClick() {
        if (dialogListener != null) {
            dialogListener.onMentionClick(user.getUsername());
        }
    }*/


    @OnClick(R.id.ll_follow)
    void onFollowBtnClick() {
        if (Utils.isTempUser(user)) {
            ConfirmDialog dialog = new ConfirmDialog(context, "提示", "不能关注临时用户");
            dialog.show();
            return;
        }
        if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
            LoginActivity.startActivity(context, "关注他需要先登录");
            return;
        }


        if (user.getUId().equals(loginUserId)) {
            return;
        }
        if (!isAttention) {
            follow(user.getuId());
            tv_follow.setText("已关注");
            isAttention = true;
            if (fansNum == null) {
                fansNum = 0L;
            }
            fansNum = fansNum + 1;
            tv_fans_num.setText(MoonUtils.getSpannableString(context, Utils.numberFormat(fansNum)));
        } else {
            removeFollow(user.getuId());
            tv_follow.setText("关注");
            isAttention = false;
            fansNum = fansNum - 1;
            if (fansNum < 0) {
                fansNum = 0L;
            }
            tv_fans_num.setText(MoonUtils.getSpannableString(context, Utils.numberFormat(fansNum)));
        }

        user.setFans(fansNum);
        user.setAttention(isAttention);
    }

    @OnClick(R.id.rl_to_user_profile)
    void onUserHomePageClick() {
        context.startActivity(new Intent(context, UserProfileActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, user).putExtra(Constant.SYNC_USER_INFO, false));

    }

    private UserDetailsDialogListener dialogListener;

    public void setUserDetailsDialogListener(UserDetailsDialogListener dialogListener) {
        this.dialogListener = dialogListener;
    }

    public interface UserDetailsDialogListener {
        void onMentionClick(String username);

        void onMessageClick(User user);
    }


    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // 使用不带theme的构造器，获得的dialog边框距离屏幕仍有几毫米的缝隙。
        // Dialog dialog = new Dialog(context);
        Dialog dialog = new Dialog(context, R.style.room_user_details_dialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // must be called before set content
        dialog.setContentView(R.layout.fragment_room_user_details);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setCanceledOnTouchOutside(true);

        // 设置宽度为屏宽、靠近屏幕底部。
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.gravity = Gravity.BOTTOM;
        wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
        wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(wlp);

        return dialog;
    }


    public void onDestroyView() {

        unbinder.unbind();
    }

    /**
     * 关注
     *
     * @param targetUid
     */
    private void follow(String targetUid) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> object = new HashMap<>();
        object.put("targetUid", targetUid);

        RetrofitManager.getInstance().createRequest(UserService.class)
                .addAttention(object).enqueue(new Callback<CommonResult>() {
            @Override
            public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                CommonResult result = response.body();
                if (!response.isSuccessful() || result == null) {
                    Log.e(TAG, "onResponse: 关注失败" + response.message());

                    return;
                }
                if (result.isError()) {
                    Log.e(TAG, "onResponse: 关注失败" + result.getMsg());

                    return;
                }
                Log.i(TAG, "onResponse: 关注成功targetUid ：" + targetUid);


            }

            @Override
            public void onFailure(Call<CommonResult> call, Throwable t) {
                Log.e(TAG, "onFailure: " + t.getMessage());

            }
        });
    }

    /**
     * 检查是否关注
     *
     * @param targetUid
     */
    private void checkFollow(String targetUid) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo_v1(targetUid)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        Object data1 = result.getData();
                        if (data1 == null) {
                            return;
                        }
                        JSONObject data = (JSONObject) data1;
                        Log.i(TAG, "onResponse: " + data.toJSONString());
                        user = data.toJavaObject(User.class);
                        isAttention = user.isAttention();
                        fansNum = user.getFans();
                        attentionSize = user.getAttentionSize();
//                        user.setFans(fansNum);
//                        user.setAttentionSize(attentionSize);
//                        user.setAttention(isAttention);
                        String donationString = Utils.moneyFormat(user.getDonationAmount());
                        tv_donationAmount.setText(MoonUtils.getSpannableString_red(context, donationString));
                        String fansString = Utils.numberFormat(fansNum);
                        tv_fans_num.setText(MoonUtils.getSpannableString(context, fansString));
                        String attentionString = Utils.numberFormat(attentionSize);
                        tv_follow_num.setText(MoonUtils.getSpannableString(context, attentionString));

                        if (isAttention) {
                            tv_follow.setText("已关注");
                        }
                    }


                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        ConfirmDialog dialog = new ConfirmDialog(context, "提示", "系统繁忙");
                        dialog.show();

                    }
                });


    }

    /**
     * 取消关注
     *
     * @param
     */
    private void removeFollow(String targetUid) {
        if (!Helper.getInstance().isNetworkConnected()) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, String> object = new HashMap<>();
        object.put("targetUid", targetUid);
        RetrofitManager.getInstance()
                .createRequest(UserService.class)
                .removeAttention(object)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());

                            return;
                        }
                        if (result.isError()) {

                            return;
                        }
                        Log.i(TAG, "onResponse: 去除关注完成 targetUid：" + targetUid);


                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        ConfirmDialog dialog = new ConfirmDialog(context, "提示", "取消关注失败");
                        dialog.show();

                    }
                });
    }


}
